<?php
//Get notes
function getnotes(){
    //Decode json and return array
    return json_decode(file_get_contents(__DIR__ . '/notes.json'), true);
}
//get selected note
function getnoteById($id){
    //get notes array
    $notes = getnotes();
    //loop through each one
    foreach ($notes as $note) {
        //check if selected id
        if ($note['id'] == $id) {
            //return note array
            return $note;
        }
    }
    //or return null
    return null;
}

//create note
function createnote($data){
    //get notes aray
    $notes = getnotes();
    //select random id?
    $data['id'] = rand(1000000, 2000000);
    //make array
    $notes[] = $data;
    //put into json
    putJson($notes);
    //return new data
    return $data;
}

function updatenote($data, $id){
    //make blank var
    $updatenote = [];
    //get notes array
    $notes = getnotes();
    //loop through each
    foreach ($notes as $i => $note) {
    // if note has equal id
        if ($note['id'] == $id) {
            //merge updated data into rray
            $notes[$i] = $updatenote = array_merge($note, $data);
        }
    }
    //put json into array
    putJson($notes);
    //return updated data
    return $updatenote;
}
//delete note
function deletenote($id){
//get notes
    $notes = getnotes();
    //loop through each note
    foreach ($notes as $i => $note) {
    //if note matches param id
        if ($note['id'] == $id) {
        //splice the array to remove that part
            array_splice($notes, $i, 1);
        }
    }
    //update json
    putJson($notes);
}

//put json
function putJson($notes){
    //put file contents (with pretty_print
    file_put_contents(__DIR__ . '/notes.json', json_encode($notes, JSON_PRETTY_PRINT));
}
?>
